#!/bin/sh

## java环境地址
export ACTIVE=dev
#export PORT=8090
export JAVA_HOME=/usr/local/jdk1.8.0
export JRE_HOME=$JAVA_HOME/jre


## 项目路径
SERVICE_DIR=`cd $(dirname $0); pwd -P`
## 服务名称
SERVICE_NAMES=(datax-eureka datax-config datax-gateway datax-auth system-service quartz-service workflow-service data-metadata-service data-metadata-service-console data-standard-service data-quality-service data-market-service data-market-service-mapping data-market-service-integration data-masterdata-service data-visual-service)
## 服务启动优先级，若2个连续进程的优先级不一致，则延迟5s启动
PRIORITY_LEVELS=(1 2 3 3 3 4 4 4 4 5 5 5 6 6 6)
## lib目录
LIBS_DIR=$SERVICE_DIR/libs
## logs目录
LOGS_DIR=$SERVICE_DIR/logs
## 进程目录
PID_DIR=$SERVICE_DIR/pid
cd $SERVICE_DIR

case "$1" in
    start)
	LENGTH=$[${#SERVICE_NAMES[*]}-1]
	OLD_LEVEL="${PRIORITY_LEVELS[0]}"
	for i in $(seq 0 1 $LENGTH);do
	SERVICE_NAME=${SERVICE_NAMES[$i]} 
	##若连续2个进程的优先级不一致，则休眠5秒
	CUR_LEVEL="${PRIORITY_LEVELS[$i]}"
	if [ "$CUR_LEVEL"a != "a" ]&&[ "$CUR_LEVEL" != "$OLD_LEVEL" ] ; then
            sleep 5
        fi
	OLD_LEVEL=$CUR_LEVEL
	echo "nohup java -jar $LIBS_DIR/$SERVICE_NAME.jar >$LOGS_DIR/$SERVICE_NAME.log 2>&1 &"
	nohup java -jar $LIBS_DIR/$SERVICE_NAME.jar >$LOGS_DIR/$SERVICE_NAME.log 2>&1 &
	echo $! > $PID_DIR/$SERVICE_NAME\.pid
	echo "=== start $SERVICE_NAME"
	done
        ;;

    stop)
	LENGTH=$[${#SERVICE_NAMES[*]}-1]
	for i in $(seq $LENGTH -1 0);do
	SERVICE_NAME=${SERVICE_NAMES[$i]} 
	kill `cat $PID_DIR/$SERVICE_NAME\.pid`
        rm -rf $PID_DIR/$SERVICE_NAME\.pid
        echo "=== stop $SERVICE_NAME"
	done
        ;;
   stop_force)
	LENGTH=$[${#SERVICE_NAMES[*]}-1]
	for i in $(seq $LENGTH -1 0);do
	SERVICE_NAME=${SERVICE_NAMES[$i]} 
	P_ID=`ps -ef | grep -w "$SERVICE_NAME" | grep java | grep -v "grep" | awk '{print $2}'`
        if [ "$P_ID" == "" ]; then
            echo "=== $SERVICE_NAME process not exists or stop success"
        else
            echo "=== $SERVICE_NAME process pid is:$P_ID"
            echo "=== begin kill $SERVICE_NAME process, pid is:$P_ID"
            kill -9 $P_ID
        fi
	done
        ;;


    restart)
        $0 stop
        sleep 2
        $0 start
        echo "=== restart success"
        ;;

    *)
        ## restart
        $0 stop
        sleep 2
        $0 start
        ;;

esac
exit 0
